<?php

namespace App\Service\Impl;

use Symfony\Component\DomCrawler\Crawler;
use App\Dto\GetListDTO;
use App\Service\ListService;
use Illuminate\Support\Facades\Http;

class ListServiceImpl implements ListService
{

    public function getContentList(GetListDTO $getListDTO,&$nextPage): array
    {

        $url = $getListDTO->getUrl();
        $parse = parse_url($url);
        $scheme = $parse["scheme"];
        $host = $parse["host"];
        $response = Http::get($url);
        $html = $response->body();
        $crawler = new Crawler($html);

        $detailURL = [];
        $crawler->filter($getListDTO->getRule())->each(function ($node) use (&$detailURL, $scheme, $host) {
            $url = $node->attr("href");
            if (!str_contains($url, "http")) {
                $url = $scheme . "://" . $host . '/' . ltrim($url, '/');
            }
            $detailURL[] = $url;
        });

        $pageRule = $getListDTO->getPageRule();
        $page = [];
        $crawler->filter($pageRule)->each(function ($node) use (&$page, $scheme, $host) {
            $url = $node->attr("href");
            if (!str_contains($url, "http")) {
                $url = $scheme . "://" . $host . '/' . ltrim($url, '/');
            }
            $page[] = $url;
        });
        // 判断是否有下一页
        $currentURLIndex = array_search($url,$page);
        $hasNext = array_key_exists($currentURLIndex + 1, $page);

        $nextPage = $hasNext ? $page[$currentURLIndex + 1] : false;
        return $detailURL;
    }
}
